package meta

import (
	jsoniter "github.com/json-iterator/go"
	"servers/models/define"
)

type CtrlMeta struct {
	Level define.CtrlLevelType
	Score define.GameScore
}

type CtrlInfos struct {
	Ctrl []CtrlMeta
}

func (v *CtrlInfos) ToJsonStr() string {
	ls := make([]any, len(v.Ctrl))
	for i := range v.Ctrl {
		var x [2]any
		x[0] = v.Ctrl[i].Level
		x[1] = v.Ctrl[i].Score
		ls[i] = x
	}
	js, _ := jsoniter.MarshalToString(ls)
	return js
}

func (v *CtrlInfos) FromJsonStr(js string) {
	var ls [][]any
	_ = jsoniter.UnmarshalFromString(js, &ls)

	if len(ls) == 0 {
		if cap(v.Ctrl) == 0 {
			v.Ctrl = make([]CtrlMeta, 1)
		}
		v.Ctrl = v.Ctrl[:1]
		v.Ctrl[0].Level = 0
		v.Ctrl[0].Score = 0
	} else {
		if cap(v.Ctrl) < len(ls) {
			v.Ctrl = make([]CtrlMeta, len(ls))
		}
		v.Ctrl = v.Ctrl[:len(ls)]
		for i, item := range ls {
			v.Ctrl[i].Level = define.CtrlLevelType(item[0].(float64))
			v.Ctrl[i].Score = define.GameScore(item[1].(float64))
		}
	}
}
